package com.hongxun.budget.ui.fragment.sg;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.sg.MaterialArriveRecordListActivity;
import com.hongxun.budget.ui.dialog.InputDialog;
import com.hongxun.budget.ui.fragment.BaseFragment;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.LocationUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.budget.utils.StringUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.sg.CStackPointEntity;
import com.hongxun.interfaces.ResponseListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 到货记录地图展示
 */
public class MaterialPresentDumpsMap extends BaseFragment {
    @BindView(R.id.sgmap)
    MapView map;
    @BindView(R.id.iv2_newpoint)
    ImageView iv2Newpoint;
    @BindView(R.id.tv4_add)
    Button tv4Add;

    private AMap aMap;
    private List<CStackPointEntity> pointEntityList = new ArrayList<>();
    private List<Marker> markerList = new ArrayList<>();
    private LatLng currentLatLng;

    @Override
    public int getLayoutId() {
        return R.layout.sg_fragment_materialpresentdumpsmap;
    }

    @Override
    public void setMapBundle(Bundle bundle) {
        map.onCreate(bundle);
    }

    @Override
    public void initView() {
        if (aMap == null) aMap = map.getMap();
        //地图中心坐标
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                currentLatLng = cameraPosition.target;
            }
        });
        //mark点击
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                for (CStackPointEntity data : pointEntityList) {
                    if (data.getSPName().equals(marker.getTitle())) {
                        SPUtils.put(context, SgStrKey.uuiddfd, data.getGuid());
                        startActivity(new Intent(context, MaterialArriveRecordListActivity.class)
                                .putExtra("pointName", data.getSPName()));
                        break;
                    }
                }
                return true;
            }
        });
    }


    @OnClick({R.id.tv4_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv4_add:
                if (tv4Add.getText().toString().contains("新增")) {
                    T.showLong(context, "拖动地图,用红色图标确定位置^_^");
                    iv2Newpoint.setVisibility(View.VISIBLE);
                    tv4Add.setText("确定");
                } else {
                    newPoint();
                }
                break;
        }
    }

    //列表与地图数据刷新
    private void newPoint() {
        new InputDialog()
                .setTitle("请输入材料堆放点名称")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .setListener(new ResponseListener() {
                    @Override
                    public void response(Object... data) {
                        //列表刷新
                        String name = data[0] + "";
                        if (!name.endsWith("堆放点")) {
                            name = name + "堆放点";
                        }
                        CStackPointEntity dfd = new CStackPointEntity();
                        dfd.setGuid(StringUtils.getUuid());
                        dfd.setPGuid(String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, "")));
                        dfd.setSPName(name);
                        dfd.setSPLatitude(currentLatLng.latitude);
                        dfd.setSPLongitude(currentLatLng.longitude);
                        dfd.setSPDatastate("新增");
                        pointEntityList.add(0, dfd);
                        //地图刷新
                        if (currentLatLng == null) {
                            showMsg("请拖动地图以获取堆放点坐标");
                            return;
                        } else {
                            setLocation();
                            GreenDaoManager.getInstance().getmDaoSession().getCStackPointEntityDao().insert(dfd);
                            iv2Newpoint.setVisibility(View.GONE);
                            tv4Add.setText("新增堆放点");
                        }
                    }
                }).show(getFragmentManager(), "");
    }

    //默认位置30.6270786740,104.1520643234
    private void setMyLocaltion() {
        new LocationUtils(context, context, 3, 0, this);
    }

    @Override
    public void success(int i, JSONObject obj) {
        double lat = obj.getDoubleValue("latitude");
        double lng = obj.getDoubleValue("longitude");
        LatLng location = new LatLng(lat, lng);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(location, 19);
        aMap.moveCamera(cameraUpdate);
    }

    public void onRefresh() {
        Observable.just(SgStrKey.uuidxm).subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
            @Override
            public Boolean call(String value) {
                pointEntityList.clear();
                String xmid = String.valueOf(SPUtils.get(context, value, ""));
                pointEntityList.addAll(SgDBUtils.getCSpListAll(xmid));
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean b) {
                aMap.clear();
                markerList.clear();
                if (pointEntityList.isEmpty()) setMyLocaltion();
                else setLocations();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        map.onResume();
        onRefresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        map.onPause();
    }

    @Override
    public void onDestroy() {
        if (map != null) map.onDestroy();
        super.onDestroy();
    }

    //新增一个物资堆放点
    private void setLocation() {
        CStackPointEntity record = pointEntityList.get(0);
        View pointView = LayoutInflater.from(context).inflate(R.layout.sg_view_map_point, null);
        LatLng location = new LatLng(record.getSPLatitude(), record.getSPLongitude());
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(location, 20);
        aMap.animateCamera(cameraUpdate);
        TextView tvTitle = pointView.findViewById(R.id.tv1);
        tvTitle.setText(record.getSPName());
        Marker marker = aMap.addMarker(new MarkerOptions()
                .position(location)
                .anchor(0.5f, 0.5f)
                .title(record.getSPName())
                .draggable(false)
                .icon(BitmapDescriptorFactory.fromView(pointView)));
        markerList.add(marker);
    }

    //地图加载堆放点位
    private void setLocations() {
        ArrayList<MarkerOptions> options = new ArrayList<>();
        for (CStackPointEntity record : pointEntityList) {
            LatLng location = new LatLng(record.getSPLatitude(), record.getSPLongitude());
            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(location, 20);
            aMap.animateCamera(cameraUpdate);
            View pointView = LayoutInflater.from(context).inflate(R.layout.sg_view_map_point, null);
            TextView tvTitle = pointView.findViewById(R.id.tv1);
            tvTitle.setText(record.getSPName());
            MarkerOptions options1 = new MarkerOptions()
                    .position(location)
                    .anchor(0.5f, 0.5f)
                    .title(record.getSPName())
                    .draggable(false)
                    .icon(BitmapDescriptorFactory.fromView(pointView));
            options.add(options1);
        }
        ArrayList<Marker> markerArrayList = aMap.addMarkers(options, true);
        if (markerArrayList != null) markerList.addAll(markerArrayList);
    }

}
